/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBLayer;

import ControlLayer.GlobalInstances;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Moulde
 */
public abstract class DatabaseAccess
{
    protected Connection dbConnection;

    public DatabaseAccess()
    {
        dbConnection = DbConnection.getInstance().getDBcon();
    }

    protected ResultSet ExecuteQuery(String sql)
    {
        try
        {
            if (GlobalInstances.getInstance().IsDebug())
            {
                Logger.getLogger(this.getClass().getName()).log(Level.INFO, sql);
            }
            return dbConnection.createStatement().executeQuery(sql);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(DBSupplier.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    protected int ExecuteNoResultQuery(String sql)
    {
        try
        {
            if (GlobalInstances.getInstance().IsDebug())
            {
                Logger.getLogger(this.getClass().getName()).log(Level.INFO, sql);
            }
            Statement statement = dbConnection.createStatement();
            return statement.executeUpdate(sql);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(DatabaseAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    protected int ExecuteNoResultQueryWithReturnValues(String sql)
    {
        try
        {
            if (GlobalInstances.getInstance().IsDebug())
            {
                Logger.getLogger(this.getClass().getName()).log(Level.INFO, sql);
            }
            Statement statement = dbConnection.createStatement();
            int result = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet generatedKeys = statement.getGeneratedKeys();

            int generatedID = 0;
            if (generatedKeys.next())
            {
                generatedKeys.getInt(1);
            }

            return generatedID;
        }
        catch (SQLException ex)
        {
            Logger.getLogger(DatabaseAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }
}
